package 蚂蚁课堂;

import org.omg.CORBA.TRANSACTION_MODE;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试多线程：
 * 由此打印可见：在ExchangerDemo中说道的在多线程的情况下有可能消息会错乱
 * t2接受到的消息是：我是t1的消息
 * t1接受到的消息是：我是t1的消息
 */
public class ExchangerDemo2 {

    private static Exchanger<String> exchanger=new Exchanger<>();

    private static AtomicBoolean atomicBoolean=new AtomicBoolean(true);

    public static void main(String[] args) {
        while (true){
            zx();
        }
    }

    public static void zx(){
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (atomicBoolean.compareAndSet(true,false)){

                    try {
                        t1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(atomicBoolean.get());
                }
                if (atomicBoolean.compareAndSet(false,true)){
                    try {
                        t2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(atomicBoolean.get());
                }
            }
        });
    }
    public static void t1() throws InterruptedException {

            String msg = exchanger.exchange("我是t1的消息");
            System.out.println("t1接受到的消息是："+msg);

    }

    public static void t2() throws InterruptedException {

            String msg = exchanger.exchange("我是t1的消息");
            System.out.println("t2接受到的消息是："+msg);

    }
}
